<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <script src="https://maps.googleapis.com/maps/api/js"></script>
<script src="js/jquery.js"></script>
<script src="js/jquery-ui.min.js"></script>
    <link href="CSS/map-setting.css" rel="stylesheet" />
    <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=places"></script>
    <title></title>
    <style>
        .controls {
            margin-top: 16px;
            border: 1px solid transparent;
            border-radius: 2px 0 0 2px;
            box-sizing: border-box;
            -moz-box-sizing: border-box;
            height: 32px;
            outline: none;
            box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
        }

        #pac-input {
            background-color: #fff;
            padding: 0 11px 0 13px;
            width: 400px;
            font-family: Roboto;
            font-size: 15px;
            font-weight: 300;
            text-overflow: ellipsis;
        }

            #pac-input:focus {
                border-color: #4d90fe;
                margin-left: -1px;
                padding-left: 14px; /* Regular padding-left + 1. */
                width: 401px;
            }

        .pac-container {
            font-family: Roboto;
        }

        #type-selector {
            color: #fff;
            background-color: #4d90fe;
            padding: 5px 11px 0px 11px;
        }

            #type-selector label {
                font-family: Roboto;
                font-size: 13px;
                font-weight: 300;
            }
    </style>

</head>
<body>
    <input id="pac-input" class="controls" type="text" placeholder="Search Box">
    <div id="google_map"></div>
</body>
</html>

    <script type="text/javascript">

        jQuery(document).ready(function () {
            var mapCenter = new google.maps.LatLng(47.6145, -122.3418); //Google map Coordinates
            var map;
            map_initialize(); // load map
            function map_initialize() {

                var MapTitle = "Add New Marker";
                var MapDesc;

                //Google map option
                var googleMapOptions =
                {
                    center: mapCenter, // map center
                    zoom: 17, //zoom level, 0 = earth view to higher value
                    panControl: true, //enable pan Control
                    zoomControl: true, //enable zoom control
                    zoomControlOptions: {
                        style: google.maps.ZoomControlStyle.SMALL //zoom control size
                    },
                    scaleControl: true, // enable scale control
                    mapTypeId: google.maps.MapTypeId.ROADMAP // google map type
                };
                map = new google.maps.Map(document.getElementById("google_map"), googleMapOptions);

                loadMarker();

                //##### drop a new marker on right click ######
                google.maps.event.addListener(map, 'rightclick', function (event) {
                    var EditForm = '<p><div class="marker-edit">' +
                          '<form action="null" method="POST" name="SaveMarker" id="SaveMarker">' +
                          '<label for="pName"><span>Place Name :</span><input type="text" name="pName" class="save-name" placeholder="Enter Title" maxlength="40" /></label>' +
                          '<label for="pDesc"><span>Description :</span><textarea name="pDesc" class="save-desc" placeholder="Enter Address" maxlength="150"></textarea></label>' +
                          '<label for="pType"><span>Type :</span> <select name="pType" class="save-type"><option value="modelTown">MODEL TOWN</option><option value="dha">DHA</option>' +
                          '<option value="gardenTown">Garden Town</option></select></label>' +
                          '</form>' +
                          '</div></p><button name="save-marker" class="save-marker">Save Marker Details</button>';

                    addMarker(event.latLng, MapTitle, EditForm, false, true, true, "css/images/pin_green.png");
                });


                //############### Search Box Functionality ##############
                var input = document.getElementById('pac-input');
                map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);

                var searchBox = new google.maps.places.SearchBox((input));
                // [START region_getplaces]
                // Listen for the event fired when the user selects an item from the
                // pick list. Retrieve the matching places for that item.
                google.maps.event.addListener(searchBox, 'places_changed', function () {
                    var places = searchBox.getPlaces();

                    if (places.length == 0) {
                        return;
                    }

                    // For each place, get the icon, place name, and location.
                    markers = [];
                    var bounds = new google.maps.LatLngBounds();
                    for (var i = 0, place; place = places[i]; i++) {
                        var image = {
                            url: place.icon,
                            size: new google.maps.Size(71, 71),
                            origin: new google.maps.Point(0, 0),
                            anchor: new google.maps.Point(17, 34),
                            scaledSize: new google.maps.Size(25, 25)
                        };

                        // Create a marker for each place.
                        var marker = new google.maps.Marker({
                            map: map,
                            icon: image,
                            title: place.name,
                            position: place.geometry.location
                        });

                        markers.push(marker);
                        bounds.extend(place.geometry.location);
                    }

                    google.maps.event.addListener(map, 'zoom_changed', function () {
                        zoomChangeBoundsListener =
                            google.maps.event.addListenerOnce(map, 'bounds_changed', function (event) {
                                if (this.getZoom() > 15 && this.initialZoom == true) {
                                    // Change max/min zoom here
                                    this.setZoom(18);
                                    this.initialZoom = false;
                                }
                                google.maps.event.removeListener(zoomChangeBoundsListener);
                            });
                    });
                    map.initialZoom = true;
                    map.fitBounds(bounds);
                   
                    
                });
                // Bias the SearchBox results towards places that are within the bounds of the
                // current map's viewport.
                //google.maps.event.addListener(map, 'bounds_changed', function () {
                //    var bounds = map.getBounds();
                //    searchBox.setBounds(bounds);
                //});


                // This is needed to set the zoom after fitbounds, 
                
            };
           

            // Function for adding a marker to the page.
            function addMarker(MapPos, MapTitle, MapDesc, InfoOpenDefault, DragAble, Removable, iconPath) {
                var marker = new google.maps.Marker({
                    position: MapPos,
                    map: map,
                    draggable: DragAble,
                    animation: google.maps.Animation.DROP,
                    title: MapTitle,
                    icon: iconPath
                });

                //Content structure of info Window for the Markers
                var contentString = $('<div class="marker-info-win">' +
                '<div class="marker-inner-win"><span class="info-content">' +
                '<h1 class="marker-heading">' + MapTitle + '</h1>' +
                MapDesc +
                '</span><button name="remove-marker" class="remove-marker" title="Remove Marker">Remove Marker</button>' +
                '</div></div>');


                //Create an infoWindow
                var infowindow = new google.maps.InfoWindow();
                //set the content of infoWindow
                infowindow.setContent(contentString[0]);

                //Find remove button in infoWindow
                var removeBtn = contentString.find('button.remove-marker')[0];

                //Find save button in infoWindow
                var saveBtn = contentString.find('button.save-marker')[0];

                //add click listner to remove marker button
                google.maps.event.addDomListener(removeBtn, "click", function (event) {
                    //call remove_marker function to remove the marker from the map
                    removeMarker(marker);
                    //marker.setMap(null);
                });

                if (typeof saveBtn !== 'undefined') //continue only when save button is present
                {
                    //add click listner to save marker button
                    google.maps.event.addDomListener(saveBtn, "click", function (event) {
                        var mReplace = contentString.find('span.info-content'); //html to be replaced after success
                        var mName = contentString.find('input.save-name')[0].value; //name input field value
                        var mDesc = contentString.find('textarea.save-desc')[0].value; //description input field value
                        var mType = contentString.find('select.save-type')[0].value; //type of marker

                        if (mName == '' || mDesc == '') {
                            alert("Please enter Name and Description!");
                        } else {
                            //call save_marker function and save the marker details
                            save_marker(marker, mName, mDesc, mType, mReplace);

                        }
                    });
                }

                //add click listner to save marker button
                google.maps.event.addListener(marker, 'click', function () {
                    infowindow.open(map, marker); // click on marker opens info window
                });

                if (InfoOpenDefault) //whether info window should be open by default
                {
                    infowindow.open(map, marker);
                }

            }

            //############### Save Marker Function ##############
            function save_marker(Marker, mName, mAddress, mType, replaceWin) {
                //Save new marker using jQuery Ajax
                var mLatLang = Marker.getPosition().toUrlValue(); //get marker position
                var myData = {
                    name: mName,
                    address: mAddress,
                    latlang: mLatLang,
                    type: mType
                }; //post variables

                console.log(replaceWin);
                $.ajax({
                    type: "POST",
                    url: '/Category/GetMapsData',
                    data: myData,
                    success: function (data) {
                        //Content structure of info Window for the Markers
                        var contentString = $('<div class="marker-info-win">' +
                        '<div class="marker-inner-win"><span class="info-content">' +
                        '<h1 class="marker-heading">' + $('.save-name').val() + '</h1>' +
                        $('.save-desc').val() +
                        '</span>' +
                        '</div></div>');

                        replaceWin.html(contentString); //replace info window with new html
                        Marker.setDraggable(false); //set marker to fixed
                        Marker.setIcon('css/images/pin_blue.png'); //replace icon
                    },
                    error: function (xhr, ajaxOptions, thrownError) {
                        alert(thrownError); //throw any errors
                    }
                });

                //$.ajax({
                //    type: "POST",
                //    url: '/Category/GetMapsData',
                //    data: { data: JSON.stringify(myData) },
                //    success: function (result) {
                //        alert(result.msg);
                //    },
                //    error: function (error) {
                //        alert('error' + error);
                //    }
                //});
            }


            //############### Function to Get Marker(s) From Databse  ##############
            function loadMarker() {
                var Mapurl = "/Category/GetSavedMaps";
                $.ajax({
                    type: "GET",
                    url: Mapurl,
                    success: function (result) {
                        for (var i = 0; i < result.length ; i++) {

                            var name = result[i].name;
                            var address = '<p>' + result[i].address + '</p>';
                            var latlang = result[i].latlang.split(",");
                            var type = result[i].type;
                            var googlePoint = new google.maps.LatLng(parseFloat(latlang[0]), parseFloat(latlang[1]));

                            addMarker(googlePoint, name, address, false, false, false, "css/images/pin_blue.png");
                        }
                    },
                    error: function (error) {
                        alert('error' + error);
                    }
                });
            }

            //############### Function to Remove Marker(s) From Databse  ##############
            function removeMarker(Marker) {
                var Mapurl = "/Category/RemoveSavedMarker";
                /* determine whether marker is draggable new markers are draggable and saved markers are fixed */
                if (Marker.getDraggable()) {
                    Marker.setMap(null); //just remove new marker
                }
                else {
                    //Remove saved marker from DB and map using jQuery Ajax
                    var mLatLang = Marker.getPosition().toUrlValue(); //get marker position
                    var myData = { delFlag: 'true', latlang: mLatLang }; //post variables
                    $.ajax({
                        type: "POST",
                        url: Mapurl,
                        data: myData,
                        success: function (data) {
                            Marker.setMap(null);
                            alert(data.msg);
                        },
                        error: function (xhr, ajaxOptions, thrownError) {
                            alert(thrownError); //throw any errors
                        }
                    });
                }
            }

        });

    </script>
